﻿/*
* XSockets.NET JavaScript Library (jXSockets.peerConnection.beta.1.0.js)
* http://xsockets.net/
* Distributed in whole under the terms of the MIT
*
* Copyright 2012, Magnus Thor & Ulf Björklund
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
/// <reference path="jXSockets.1.0.6.beta.js" />
var XSocketsWebRtc = function (stunServer, signalServer) {
    "use strict";

    var self = this;

    var stream = null;
    var signalController;
    var dispatch = {};
    var peer = [];
    var signal = {
        By: "",
        For: "",
        Message: ""
    };
    var settings = {
        stun: stunServer
    };


    this.Events = {
        Incomming: "incomming",
        Outgoing: "outgoing",
        Completed: "completed"
    };
    var pc = 0;
    signalController = new XSockets.WebSocket(signalServer, "WebRTC");
    signalController.bind(XSockets.Events.onError, function (err) {
        console.log("#error", err);
    });

    // Create a new PeerConnection
    var peerConnection = function (server, fn) {

        if ("webkitDeprecatedPeerConnection" in window) {
            return new window.webkitDeprecatedPeerConnection(server, fn);
        } else {
            return new window.webkitPeerConnection(server, fn);
        }
    };

    signalController.bind("onpeercreated", function (msg) {
        dispatchTo("peercreated", msg);
    });
    signalController.bind("onpeerconnected", function (msg) {
        dispatchTo("peerconnected", msg);
    });

    signalController.bind("onnumofpeerschanged", function (msg) {
        dispatchTo("peerschanged", msg);
    });



    signalController.bind("onstart", function (msg) {
        dispatchTo("start", msg);
    });


    signalController.bind("ontalks", function (msg) {
        dispatchTo("talks", msg);
    });

    // WebSockets (XSockets messages)
    signalController.bind(XSockets.Events.open, function () {

        signalController.one("onanswer", function (msg) {
            peer[pc].processSignalingMessage(msg.Message);
        });
        signalController.one("oncompleted", function (msg) {
            peer[pc].processSignalingMessage(msg.Message);
        });
        signalController.one("onoffer", function (msg) {
            peer.push(new peerConnection(settings.stun, peerOpen));
            peer[pc].addStream(stream);
            peer[pc].onaddstream = onRemoteStreamAdded;
            peer[pc].onremovestream = onRemoteStreamRemoved;
            signal.By = msg.For;
            signal.For = msg.By;
            peer[pc].processSignalingMessage(msg.Message);
        });



    });
    // messageType 'OFFER'
    dispatch.offer = function (msg) {
        signal.Message = msg;

        signalController.trigger("offer", signal, function () {
            dispatchTo(self.Events.Outgoing, signal.Message);
        });
    };
    // messageType 'OK'
    dispatch.ok = function (msg) {
        signal.Message = msg;
        signalController.trigger("complete", signal, function () {
            dispatchTo(self.Events.Completed, signal.Message);
        });
    };
    // messageType 'ANSWER'
    dispatch.answer = function (msg) {
        signal.Message = msg;
        //        dispatchTo(self.Events.Incomming, signal);
        signalController.trigger("answer", signal, function (m) {
            dispatchTo(self.Events.Incomming, signal.Message);
        });
    };

    /// Call accepted 
    this.complete = function (msg) {
        // signalController.trigger("answer", msg);
    };
    // Dispatch the PeerConnection SignalingMessages
    var proccessMessage = function (msg) {
        var json = msg.substr(4, msg.length);
        var spd = JSON.parse(json);
        dispatchTo(spd.messageType.toLocaleLowerCase(), (msg));
    };

    var peerOpen = function (msg) {
        proccessMessage(msg);
    };
    var onRemoteStreamAdded = function (event) {
        dispatchTo("remotestream", event);
    };

    var onRemoteStreamRemoved = function (event) {

    };

    var dispatchTo = function (event, msg) {
        if (dispatch[event] !== undefined) dispatch[event](msg);
    };

    this.bind = function (event, fn) {
        dispatch[event] = fn;
    };

    this.connect = function (a, b) {
        signalController.trigger("start", {
            Identity: b
        });

        signal.For = b;
        signal.By = a;
        peer.push(new peerConnection(settings.stun, peerOpen));
        peer[pc].onaddstream = onRemoteStreamAdded;
        peer[pc].addStream(stream);
        peer[pc].onremovestream = onRemoteStreamRemoved;

    };

    this.disconnect = function () {
        peer[pc] = null;
    };

    this.Inititalize = function (data) {
        signal.By = data.Identity;
        signalController.trigger("setnick", data);
    };
    /// Get the UserMeida 
    this.getUserMedia = function (fn) {
        try { // Chrome > 18
            navigator.webkitGetUserMedia({
                audio: true,
                video: true
            }, function (srm) {
                stream = srm;
                fn(window.webkitURL.createObjectURL(srm));
            }, function (err) {
                dispatchTo("error", err);
            });
        } catch (e) { // Chrome 18.x
            navigator.webkitGetUserMedia("video,audio", function (srm) {
                stream = srm;
                fn(window.webkitURL.createObjectURL(srm));
            }, function (err) {
                dispatchTo("error", err);
            });
        }
    };
};